package com.microservice.skeleton.auth.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.microservice.skeleton.auth.util.DataTypeChange;

/**
 * Created by Mr.Yangxiufeng on 2017/12/27.
 * Time:17:02
 * ProjectName:Mirco-Service-Skeleton
 */
@Controller
public class HelloController {
	
	
	 @Value("${oauthUrl}")
	 private String oauthUrl ;
	
	
	
	
	
	
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/hello")
    public String hello() {
        return "order";
    }
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
    
    
    
    
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)
    public String doLogin(Map<String, Object> param,String username,String password,String url,String clientUserName,String clientPassword){
        System.out.println(username);
        
        //		getUserData("http://localhost:9030/uaa/oauth/token?grant_type=password&username=admin&password=123456","webApp1","webApp2");

    	try {
    		BasicHttpParams httpParams = new BasicHttpParams();
    		HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
    		HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
    		DefaultHttpClient client = new DefaultHttpClient(httpParams);
    		HttpPost post = new HttpPost(oauthUrl+"?grant_type=password&username="+username+"&password="+password);
    		post.setHeader("Content-Type", "application/json");
    		//浣跨敤base64杩涜鍔犲瘑
    		byte[] tokenByte = Base64.encodeBase64((clientUserName+":"+clientPassword).getBytes());
    		//灏嗗姞瀵嗙殑淇℃伅杞崲涓簊tring
    		String tokenStr = DataTypeChange.bytesSub2String(tokenByte, 0, tokenByte.length);
    		//Basic YFUDIBGDJHFK78HFJDHF==    token鐨勬牸寮?
    		String token = "Basic "+tokenStr;
    		//鎶婅璇佷俊鎭彂鍒癶eader涓?	
    		System.out.println(token);
    		post.setHeader("Authorization", token);
    		HttpResponse response = client.execute(post);
    		int statusCode = response.getStatusLine().getStatusCode();
    		String retSrc = EntityUtils.toString(response.getEntity(), "utf-8");
    		System.out.println(retSrc);
            JSONObject jsonObject = JSON.parseObject(retSrc);
            System.out.println(jsonObject.getString("access_token"));
            
           // Map<String, Object> param  = new HashMap<String ,Object>();
            System.out.println(statusCode);
    		if(statusCode==200) {
    			return url;
    		}else {
    			param.put("error", "请求异常");
    			return "login";
    		} 
    			
    			
    		
    		
    		//JSONObject jsStr = JSONObject.parseObject(requestBody); //将字符串{“id”：1}

    		/*Log.i("Tag", "url=="+url);
    		Log.i("Tag", "===statuscode==="+statusCode+"===retsrc==="+retSrc);*/
    	} catch (UnsupportedEncodingException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (ClientProtocolException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
		return "login";

    } 
}
